import { Router } from "express";
import { sendVerificationCode, verifyCode } from "../services/emailService";

const router = Router();

// 发送验证码
router.post("/send-code", async (req, res) => {
  try {
    const { email } = req.body;

    if (!email) {
      return res.status(400).json({
        success: false,
        message: "邮箱地址不能为空"
      });
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return res.status(400).json({
        success: false,
        message: "请输入有效的邮箱地址"
      });
    }

    // 发送验证码
    const result = await sendVerificationCode(email);

    if (result.success) {
      return res.json({
        success: true,
        message: result.message,
        // 开发环境返回验证码用于测试
        ...(process.env.NODE_ENV === 'development' && { code: result.code })
      });
    } else {
      return res.status(500).json({
        success: false,
        message: result.message
      });
    }

  } catch (error) {
    console.error("发送验证码失败:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误，请稍后重试"
    });
  }
});

// 验证验证码
router.post("/verify-code", async (req, res) => {
  try {
    const { email, code } = req.body;

    if (!email || !code) {
      return res.status(400).json({
        success: false,
        message: "邮箱地址和验证码不能为空"
      });
    }

    // 验证验证码
    const result = verifyCode(email, code);

    return res.json({
      success: result.success,
      message: result.message
    });

  } catch (error) {
    console.error("验证码验证失败:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误，请稍后重试"
    });
  }
});

// 重置密码
router.post("/reset-password", async (req, res) => {
  try {
    const { email, code, newPassword } = req.body;

    if (!email || !code || !newPassword) {
      return res.status(400).json({
        success: false,
        message: "邮箱地址、验证码和新密码都是必填项"
      });
    }

    // 验证验证码
    const verifyResult = verifyCode(email, code);
    if (!verifyResult.success) {
      return res.status(400).json({
        success: false,
        message: verifyResult.message
      });
    }

    // 导入用户数据库
    const { userDb } = require('../routes/auth');
    
    // 查找用户
    let targetUser = null;
    for (const [userId, user] of userDb.entries()) {
      if (user.email === email) {
        targetUser = user;
        break;
      }
    }

    if (!targetUser) {
      return res.status(404).json({
        success: false,
        message: "未找到该邮箱对应的用户"
      });
    }

    // 导入密码哈希函数
    const crypto = require('crypto');
    function hashPassword(password: string): string {
      return crypto.createHash('sha256').update(password).digest('hex');
    }

    // 更新密码
    targetUser.password = hashPassword(newPassword);
    userDb.set(targetUser.id, targetUser);

    console.log(`[密码重置] 用户 ${targetUser.username} 密码已重置`);

    return res.json({
      success: true,
      message: "密码重置成功"
    });

  } catch (error) {
    console.error("密码重置失败:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误，请稍后重试"
    });
  }
});

// 测试邮件服务
router.get("/test", async (req, res) => {
  try {
    const testEmail = "test@example.com";
    const result = await sendVerificationCode(testEmail);

    return res.json({
      success: true,
      message: "邮件服务测试完成",
      result: result
    });

  } catch (error) {
    console.error("邮件服务测试失败:", error);
    return res.status(500).json({
      success: false,
      message: "邮件服务测试失败",
      error: error instanceof Error ? error.message : String(error)
    });
  }
});

export default router;
